$(function() {

	// 全局变量
	window.showScanLpn = false;
	var $thisStepTip = $("#secondTip");
	window.selectId = null;
	window.curMpAndResidueQty = "";// 当前位置可备料总数
	window.$gridTable = $("#pdaTable");
	window.$gridTableUn = $("#pdaTable");
	window.isDmReq = false;

	// 初始化表格数据
	window.initCompGridData = function(extend) {
		$gridTableUn.jqGrid("clearGridData");
		$gridTableUn.setGridParam({
			data : extend.compListUn
		}).trigger("reloadGrid");

		if (extend.isDmReq) {
			isDmReq = true;
			// 隐藏工单
			$gridTableUn.setGridParam().hideCol("moCode");
			$gridTableUn.setGridParam().hideCol("mainCode");
		} else {
			// 显示工单
			$gridTableUn.setGridParam().showCol("moCode");
			$gridTableUn.setGridParam().showCol("mainCode");
		}
	}

	// 初始化表格
	addLoadEvent(function() {
		// 初始化jqgrid
		jqgridInit('#pdaTable', options = {
			datatype : "local",
			height : "300px",
			rowNum : 100000,
			colNames : colNames,
			colModel : colModel,
			multiboxonly : true,
			autoScroll : true,
			shrinkToFit : false,
			gridComplete : function() {
				tableUtils.showPageNumb($gridTable);
			},
			loadComplete : function(data) {
				appUtils.initAppPage($gridTable, colModel, "", $(".initTable .dropdown-li"));
			}
		});
	})

	// 动作点击事件
	$("#tableLi").on("click", ".dropdown-menu a,[event=icon-list]", function(e) {
		var type = $(this).attr("id");
		var rowId = $(this).attr("rowId");
		var ids = $gridTable.jqGrid("getGridParam", "selarrrow");
		if (rowId) {
			$gridTable.jqGrid("resetSelection");
			$gridTable.jqGrid("setSelection", rowId);
		}
		if (!rowId && ids.length > 0) {
			rowId = ids[0];
			if (ids.length > 1) {
				rowId = ids[0];
			}
		}
		if (!rowId && ids.length == 0) {
			rowId = $gridTable.jqGrid("getDataIDs")[0];
		}
		if(!rowId){
			AlertVoice.operateFailed(i18n.selectOneRecord);	
			return;		
		}
		selectId = rowId;
		if (type == "spare") {
			$thisStepTip.hide();
			spareFunc(rowId);// 备料
		} else if (type == "recommend") {
			recommendFunc(rowId);// 推荐
		} else if (type == "refresh") {
			getMtrlInfoByLpn();
		}
	})

	// 推荐
	function recommendFunc(rowId) {
		var rowData = $gridTable.jqGrid("getRowData", rowId);
		rowData.recoType = 0;
		rowData.storeId = $("#storeId").val();
		rowData.orgId = $("#orgId").val();
		if ($("[name=mpAllByOne]:checked").length == 1) {
			rowData.mpAllByOne = "Y";
		} else {
			rowData.mpAllByOne = "N";
		}
		if ($("[name=showAllMtrlList]:checked").length == 1) {
			rowData.isShowAllMtrlList = "Y";
		} else {
			rowData.isShowAllMtrlList = "N";
		}
		if (!isDmReq) {
			// moId为空，则moCode是工单组
			rowData.moId = $("#moId").val();
			rowData.moCode = $("#moCode").val();
		}
		recommend({
			data : rowData
		});// 推荐
		$("#tableLi,#showAllMtrlListDiv").addClass("hidden");
	}

	// 删除当前行并备料下一行工单
	window.delCurRowAndSpare = function(oldSelectId, extend) {
		// 查询物料信息
		RestfulClient.post(urlGetMtrlInfoByLpn, {
			form : getPostData()
		}, function(data) {
			var dtoList = data.extend.compListUn;
			if (dtoList && dtoList.length > 0) {
				initCompGridData(data.extend);

				curLocMap = {};
				for ( var i in dtoList) {
					var thisRowId = parseInt(i) + 1;
					var dto = dtoList[i];
					var otherPosLoc = unSuc + curSeprate + dto.mtrlId;
					curLocMap[otherPosLoc] = thisRowId;
					// 未完成的key
					var thisNoPosKey = unSuc + curSeprate + dto.mainId;
					var thisNoPosValueArr = [];
					if (allLocMap[thisNoPosKey]) {
						thisNoPosValueArr = allLocMap[thisNoPosKey];
					}
					thisNoPosValueArr.push(thisRowId);
					allLocMap[thisNoPosKey] = thisNoPosValueArr;
				}
				var ids = $gridTable.jqGrid("getDataIDs");
				if(ids[oldSelectId-1]){
					// 备料下一条
                    selectId = ids[oldSelectId-1];
					$gridTable.jqGrid("setSelection", ids[oldSelectId-1]);
					spareFunc(ids[oldSelectId-1]);
				}else{
					// 选中第一条
                    selectId = 1;
					$gridTable.jqGrid("setSelection", ids[0]);
					// 备料第一条
					spareFunc(ids[0]);
				}

			} else {
				
				// 回到工单选择页面
				$("#secondLi,#skip,#prev,.recoTable").addClass("hidden");
				$("#selectLi,#ok,#moGroupBtn,#mpAllByOneDiv").removeClass("hidden");
				$(".operBtn button:not(#ok,#moGroupBtn),#tableLi,.recoTable").addClass("hidden");
				$("#moCode").val("");
				
				//查询是否包装推料发送
//				setTimeout(function() {
//					AlertVoice.customConfirm(i18n.titleConfirm,'是否将箱号：' + containerLpn + '包装推料', function() {
//						// 查询物料信息
//						RestfulClient.post(packMnMtrl, {
//							form : getPostData()
//						}, function(data) {
//							//alert(data);
//							swal.close();
//							// 回到工单选择页面				
//							$("#secondLi,#skip,#prev,.recoTable,#scanSwhDevCode,#scanLpnBtn,#selectLi,#ok,#mpAllByOneDiv,#moGroupBtn").addClass("hidden");
//							$("#scanRoLi").removeClass("hidden");
//							$(".operBtn button:not(#ok,#moGroupBtn),#tableLi,#showAllMtrlListDiv,.recoTable").addClass("hidden");
//							$("#moCode").val("");
//							$("#containerLpn").val("");						
//							
//						})						
//					});	
//				}, 500);				
							
			}
		})
	}

	// 备料
	window.spareFunc = function(rowId, isShow) {
		//$thisStepTip.hide();
		$("#tableLi,#showAllMtrlListDiv,#reco,.slocTabel,#selectMo,#isWhole,#isWholePrepare").addClass("hidden");
		$("#secondLi,#skip,#retur,#print,#scanSwhDevCode,#scanLpnBtn").removeClass("hidden");

		var rowData = $gridTable.jqGrid("getRowData", rowId);
		// 优先当前位置备料数据
		var curPosLoc = cur + curSeprate + rowData.mtrlId;
		// 当前列表转存map对象，用于物料定位
		curLocMap[curPosLoc] = rowId;

		var mpData = {
			orgId : $("#orgId").val()
		};
		if ($("[name=mpAllByOne]:checked").length == 1) {
			mpData.mpAllByOne = "Y";
		} else {
			mpData.mpAllByOne = "N";
		}
		if (!isDmReq) {
			mpData.moId = rowData.moId;
			mpData.moCode = rowData.moCode;
		} else {
			// moId为空，则moCode是工单组
			mpData.moId = $("#moId").val();
			mpData.moCode = $("#moCode").val();
		}
		mpData.mtrlId = rowData.mtrlId;
		mpData.mainId = rowData.mainId;
		var getMpUrl = subContextPath + "/getMpAndResidueNum";
		RestfulClient.post(getMpUrl, mpData, function(data) {
			$("#scanInfoMoCode").text($("#moCode").val());
			$("#scanInfoMtrlCode").text(rowData.mtrlCode);
			var residueQty = data.data.residueQty;
			if (residueQty >= 0) {
				$("#scanInfoMpAndResidueLabel").text(i18n_mpAndResidue);
			} else {
				$("#scanInfoMpAndResidueLabel").text(i18n_mpAndOver);
				residueQty = Math.abs(residueQty);
			}
			$("#scanInfoMpAndResidue").text(data.data.mpQty + " / " + residueQty);
			$("#scanInfoNeedQty").text(data.data.demandQty);
			$(".mtrlMainInfoHeaderDiv").hide();
			if (mpData.moId){
				// 非工单组备料显示
				$(".mtrlMainInfoHeaderDiv").show();
				showMainSku(data.extend);
			}

			if (!isShow) {
				//$("#lpnQrcode").parent().parent().find("label").text(i18n_scanLpn);
				//$("#lpnQrcode").val("").focus();
			
				// 获取锁定的仓储设备编码信息
				//getLockSwhDevCodeInfo();
			}
			// initFirstStepScanMpLpnQrcode();
		})

		// 推荐信息
		mpData.recoType = 1;
		if ($("[name=showAllMtrlList]:checked").length == 1) {
			mpData.isShowAllMtrlList = "Y";
		} else {
			mpData.isShowAllMtrlList = "N";
		}
		var getRecommendUrl = subContextPath + "/getRecommend";
		RestfulClient.post(getRecommendUrl, {
			"data" : mpData
		}, function(data) {
			var recommendList = data.data;
			if (recommendList == null) {
				$("#scanLpnBtn").click();
				$("#recommendInfoDiv").hide();
				layerUtils.pdaError($thisStepTip, data.resultMsg);
				return;
			}
			$("#recommendInfoDiv").show();
			if (recommendList && recommendList.length > 0) {
				var curData = recommendList[0];
				//仓库名称
				$("#scanInfoStoreAndSub").text((curData.storeCode == null ? "" : curData.storeCode) + " / " + (curData.storesubCode == null ? "" : curData.storesubCode));
				$("#scanInfoRackAndLoc").text((curData.storerackCode == null ? "" : curData.storerackCode) + " / " + (curData.storelocCode == null ? "" : curData.storelocCode));
				$("#scanInfoLpn").text(curData.lpn == null ? "" : curData.lpn);
			var urlgetStock = contextPath + "/wmsstocklock" + "/findMtrlStockByLpn";
			$("#mnStoreBoxOne").html("");
			$("#storeAllNum").text("");	
				/*
				var tableHtml = '';
				for(var i =0; i< recommendList.length; i++){
					var d = recommendList[i];
					tableHtml+="<tr style='margin-left:20px;margin-top:10px;'><td>"+curData.storeCode+"</td><td>"+curData.mtrlLev+"</td></tr> ";
				}
				*/
				RestfulClient.post(urlgetStock, {
					  extend : {
						"org" : $("#orgId").val() || $("#orgId").text(),
						"lpn" : "",
						"optType":"2",
						"mtrlCode" : rowData.mtrlCode,
						"moId":$("#moCode").val()
					}
				}, function(data) {
					if(!!data&&!!data.data){
						var hdDto = data.data;
						var stockList = hdDto.lpnStocks;
						if(!!stockList){
							var tableHtml = '';
							for(var i =0; i< stockList.length; i++){
								var d = stockList[i];
								tableHtml+="<tr style='margin-left:20px;margin-top:10px;'><td>"+d.storeCode+"</td><td>"+(d.lotno==null?"":d.lotno)+"</td><td>"+d.lpnQty+"</td></tr> ";
							}
							$("#mnStoreBoxOne").html(tableHtml);
						}
						//库存总数量
						$("#storeAllNum").text(!data.data.sumQty?0:data.data.sumQty);					
					}
					$("#scanInfoLotno").text(curData.erpLotno == null ? "" : curData.erpLotno);
					if (curData.skuCode == null || curData.isUseSku == "") {
						$("#scanInfoSku").parent().parent().parent().hide();
					} else {
						$("#scanInfoSku").text(curData.skuCode == null ? "" : curData.skuCode).parent().parent().parent().show();
					}
					//物料编码
					$("#scanInfoRecommendMtrlCode").text(curData.mtrlCode);
					$("#scanInfoRecommendMtrlName").text(curData.mtrlName);
					$("#scanInfoSwhDevCode").text(curData.swhDevCode == null ? "-" : curData.swhDevCode);
					
					if (!isShow) {
						// 盲扫 选择
						if(curData.swhDevCode != null && !showScanLpn){
							$("#scanSwhDevCode").click();
						}else{
							$("#scanLpnBtn").click();
							pageData = {
								type : step.lpn
							};
						}
					}
				});
			}
		});
	}
	/**
	 * 显示主副料SKU需求信息
	 */
	function showMainSku(extend) {
		var list = extend.sku;
		var isSku = extend.isSku;
		var divHtml = '';
		for (var i = 0; i < list.length; i++) {
			var data = list[i];
			divHtml += '<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">';
			divHtml += '	<div class="form-group">';
			if (data.isMain == "Y") {
				divHtml += '<label>' + i18n_mainMtrl + ':  </label>';
			} else {
				divHtml += '<label>' + i18n_indirectMtrl + ':  </label>';
			}
			if (isSku) {
				if (data.demandQty <= 0) {
					var errorMsg = "";
					if (data.demandQty == -1) {
						// 物料编码：{0}指定SKU：{1}，但与工单分配SKU不匹配。
						errorMsg = error_mtrlCodeNoInMo + "";
					} else if (data.demandQty == 0) {
						// 物料编码：{0}指定SKU：{1},但需求为0；
						errorMsg = error_mtrlCodeNeedZero + "";
					}
					errorMsg = errorMsg.replace("{0}", data.mtrlCode).replace("{1}", data.skuCode);
					divHtml += '	</div>';
					divHtml += '</div>';
					divHtml += '<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">';
					divHtml += '	<div class="form-group">';
					divHtml += '		<label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + errorMsg + '  </label>';
					divHtml += '	</div>';
					divHtml += '</div>';
					continue;
				}
			}
			divHtml += '	</div>';
			divHtml += '</div>';
			divHtml += '<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">';
			divHtml += '	<div class="form-group">';
			divHtml += '		<label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + i18n_mtrlCode + ': <span>' + data.mtrlCode + '</span>  </label>';
			divHtml += '	</div>';
			divHtml += '</div>';
			if (isSku) {
				// if(data.skuCode==null || data.skuCode.trim()==""){
				// 供应商编码：xxx
				if (data.supCode != null && data.supCode.trim() != "") {
					divHtml += '<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">';
					divHtml += '	<div class="form-group">';
					divHtml += '		<label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + i18n_supCode + ': <span>' + data.supCode + '</span>  </label>';
					divHtml += '	</div>';
					divHtml += '</div>';
				}
				// SKU/剩余数量：xxx / xxx ,当SKU未超时，显示剩余数量，否则显示超发数量
				var residueQtyTextName = i18n_residueQty;
				var residueQty = data.residueQty;
				if (residueQty < 0) {// 超发
					residueQtyTextName = i18n_bloQty;
					residueQty = Math.abs(residueQty);
				}
				divHtml += '<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">';
				divHtml += '	<div class="form-group">';
				divHtml += '		<label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;SKU/' + i18n_needQty + ': <span>' + data.skuCode + '&nbsp;&nbsp;/&nbsp;&nbsp;' + residueQty + '</span>  </label>';
			} else {
				// 需求数量：xxx
				divHtml += '<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">';
				divHtml += '	<div class="form-group">';
				divHtml += '		<label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + i18n_needQty + ': <span>' + data.demandQty + '</span>  </label>';
			}
			divHtml += '	</div>';
			divHtml += '</div>';
		}
		$("#mtrlMainInfoDiv").html(divHtml);
	}

	// 跳过
	$("#skip").click(function() {
		if(pageData.bsSwhDevId){
			// 扫描了仓储设备，跳过无效
			$("#lpnQrcode").val("").focus();
			return;
		}
		var ids = $gridTable.jqGrid("getDataIDs");
		for (var i = 0; i < ids.length; i++) {
			if (ids[i] == selectId) {
				var index = i + 1;
				selectId = index == ids.length ? ids[0] : ids[index];
				break;
			}
		}
		$gridTable.jqGrid("resetSelection");
		$gridTable.jqGrid("setSelection", selectId);
        $thisStepTip.hide();
		spareFunc(selectId);
		$("#lpnQrcode").val("").focus();
	})

	// 窗口发生变化
	$(window).resize(function() {
		$gridTable.setGridWidth($(".stepCenter").width());
	});

}($))